package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.Card
import com.example.cardgame.model.CardMatchingGame

class CardGameActivity : AppCompatActivity() {
    private lateinit var buttons: List<Button>
    private lateinit var scoreTextView: TextView
    private lateinit var game: CardMatchingGame
    private val clickCounts = mutableMapOf<Button, Int>()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)
        title = getString(R.string.card_game)

        game = CardMatchingGame(16)
        scoreTextView = findViewById(R.id.score)
        updateScore()

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        buttons = (0 until gridLayout.childCount).map { gridLayout.getChildAt(it) as Button }

        buttons.forEachIndexed { index, button ->
            clickCounts[button] = 0
            button.setOnClickListener {
                clickCounts[button] = clickCounts[button]!! + 1
                updateButtonText(button, game.cardAtIndex(index), clickCounts[button]!!)
                chooseCardAtIndex(index)
                updateScore()
            }
        }

        val resetButton = findViewById<Button>(R.id.reset)
        resetButton.setOnClickListener {
            resetGame()
        }

        val exitButton = findViewById<Button>(R.id.exit)
        exitButton.setOnClickListener {
            exitGame()
        }
    }

    private fun updateButtonText(button: Button, card: Card, clickCount: Int) {
        if (clickCount % 2 == 1) {
            button.setBackgroundColor(Color.WHITE)
            button.text = card.toString()
        } else {
            button.setBackgroundResource(R.drawable.card_background)
            button.text = ""
        }
    }

    private fun updateScore() {
        scoreTextView.text = getString(R.string.score) + game.score
        updateHighScoreIfNeeded()
    }

    private fun chooseCardAtIndex(index: Int) {
        game.chooseCardAtIndex(index)
        val card = game.cardAtIndex(index)
        if (card.isMatched) {
            updateButtonAppearance(buttons[index], true)
            for (otherCard in game.cards) {
                if (otherCard.isMatched && otherCard != card) {
                    val otherIndex = game.cards.indexOf(otherCard)
                    updateButtonAppearance(buttons[otherIndex], true)
                }
            }
        }
    }

    private fun updateButtonAppearance(button: Button, isMatched: Boolean) {
        if (isMatched) {
            button.setTextColor(Color.DKGRAY)
            button.isEnabled = false
        }
    }

    private fun resetGame() {
        val currentScore = game.score
        if (currentScore > getHighScore()) {
            saveHighScore(currentScore)
        }
        game = CardMatchingGame(16)
        updateScore()
        buttons.forEachIndexed { index, button ->
            clickCounts[button] = 0
            button.setBackgroundResource(R.drawable.card_background)
            button.text = ""
            button.setTextColor(Color.BLACK)
            button.isEnabled = true
        }
        returnHighScore(currentScore)
    }

    private fun getHighScore(): Int {
        val sharedPreferences = getSharedPreferences("game_prefs", MODE_PRIVATE)
        return sharedPreferences.getInt("high_score", 0)
    }

    private fun saveHighScore(score: Int) {
        val sharedPreferences = getSharedPreferences("game_prefs", MODE_PRIVATE)
        with(sharedPreferences.edit()) {
            putInt("high_score", score)
            apply()
        }
    }

    private fun returnHighScore(score: Int) {
        val data = Intent()
        data.putExtra("score", score)
        setResult(RESULT_OK, data)
    }

    private fun exitGame() {
        val currentScore = game.score
        val highScore = getHighScore()
        if (currentScore > highScore) {
            saveHighScore(currentScore)
        }
        returnHighScore(currentScore)
        finish()
    }

    override fun finish() {
        returnHighScore(game.score)
        super.finish()
    }

    private fun updateHighScoreIfNeeded() {
        val currentScore = game.score
        val intent = Intent()
        intent.putExtra("score", currentScore)
        setResult(RESULT_OK, intent)
    }
}